﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Data;
using PlanningGIS.ManageUtility.DataAccess;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.ManageUtility;
using DevComponents.AdvTree;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 角色管理控件
    /// </summary>
    public partial class CtlRoles : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlRoles()
        {
            InitializeComponent();
        }
        
        /// <summary>
        /// 之前选择的行
        /// </summary>
        private int _OldIndex = -1;

        /// <summary>
        /// 是否改变
        /// </summary>
        private bool _Changed = false;

        /// <summary>
        /// 
        /// </summary>
        private BillCommands _Commands;

        /// <summary>
        /// Gets or sets the commands associated with the control.
        /// </summary>
        public BillCommands Commands
        {
            get { return _Commands; }
            set
            {
                if (value != _Commands)
                {
                    BillCommands oldValue = _Commands;
                    _Commands = value;
                    OnCommandsChanged(oldValue, value);
                }
            }
        }

        /// <summary>
        /// Called when Commands property has changed.
        /// </summary>
        /// <param name="oldCmd">Old property value</param>
        /// <param name="newCmd">New property value</param>
        protected virtual void OnCommandsChanged(BillCommands oldCmd, BillCommands newCmd)
        {
            btnSave.Command = newCmd != null ? newCmd.RoleCommands.Save : null;
            btnCancel.Command = newCmd != null ? newCmd.RoleCommands.Cancel : null;
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        public void BindData()
        {
            _OldIndex = -1;
            try
            {                
                ctlRegion1.LoadControl();
                Hash_Table ht = ManageHelper.GetHash_Table(ManageHelper.KEY_FUNCTION);
                if (ht != null)
                    funcTree.ReadXml(Encoding.UTF8.GetString(ht.Value), true);
                ht = ManageHelper.GetHash_Table(ManageHelper.KEY_TOC);
                if (ht != null)
                    tocTree.ReadXml(Encoding.UTF8.GetString(ht.Value), true);
                resourceTree.BindData(true);
                mxdTree1.BindData(true);
                dgrdvwRoles.Rows.Clear();
                List<Role> roles = ManageHelper.DBContext.GetAllEntry<Role>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (Role r in roles)
                    {
                        int idx = dgrdvwRoles.Rows.Add(new string[] { r.Name, r.ID });
                        dgrdvwRoles.Rows[idx].Tag = r;
                    }
                    SetRole(0);
                }
                
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("打开文件失败,可能规则文件格式不正确:" + ex.Message);
            }
            finally
            {
                _Changed = false;
            }
        }
        
        /// <summary>
        /// 刷新控件
        /// </summary>
        public void RefreshControl()
        {
            tbitmExtent.Visible = ManageHelper.RegionStarted;
            _Changed = false;
            funcTree.ResetControl();
            tocTree.ResetControl();
            resourceTree.ResetControl();
            mxdTree1.ResetControl();
            ctlRegion1.ResetControl();            
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddRole_Click(object sender, EventArgs e)
        {
            FrmAddRole frm = new FrmAddRole();
            if (frm.ShowDialog(this) != DialogResult.OK) return;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                SaveChange();
                Application.DoEvents();
                Role r = new Role()
                {
                    ID = Guid.NewGuid().ToString(),
                    Name = frm.RoleName
                };
                int rst = ManageHelper.DBContext.Insert<Role>(r);
                if (rst < 1)
                {
                    MsgHelper.ShowErrorMsgbox("操作失败：" + ManageHelper.DBContext.Message);
                    return;
                }
                Application.DoEvents();
                int idx = dgrdvwRoles.Rows.Add(new string[] { frm.RoleName, r.ID });
                dgrdvwRoles.Rows[idx].Tag = r;
                SetRole(idx);
                Application.DoEvents();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        /// <summary>
        /// 单击单元格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwRoles_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (e.ColumnIndex == dgrdvwcolOp.Index)
                {
                    if (dgrdvwRoles.Rows[e.RowIndex].Tag == null) return;
                    if (MsgHelper.ShowYesOrNoQueryMsgBox("是否确定要删除选择的角色？") != DialogResult.Yes) return;
                    Role r = (Role)dgrdvwRoles.Rows[e.RowIndex].Tag;
                    int rst = ManageHelper.DBContext.Delete(
                             new List<string> { "role", "USER_ROLE_REL", "ROLE_REL" },
                             new List<string> { r.ID, r.ID, r.ID },
                             new List<string> { "id", "role_id", "roleid" });
                    if (rst > 0)
                    {
                        if (_OldIndex == e.RowIndex)
                        {
                            _Changed = false;
                            _OldIndex = -1;
                        }
                        dgrdvwRoles.Rows.RemoveAt(e.RowIndex);
                        if (dgrdvwRoles.Rows.Count > 0) SetRole(0);
                    }

                }
                else
                {
                    if (_OldIndex != e.RowIndex)
                    {
                        SaveChange();
                        SetRole(e.RowIndex);
                    }

                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
                return;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 设置当前的角色值
        /// </summary>
        private void SetRole(int rowindex)
        {
            if (dgrdvwRoles.RowCount <= rowindex || rowindex < 0) return;
            if (dgrdvwRoles.Rows[rowindex].Tag == null) return;            
            _OldIndex = rowindex;
            Role r = (Role)dgrdvwRoles.Rows[rowindex].Tag;
            funcTree.SetEnableAll(RoleAccess.GetRoleFuncRel(r.ID), funcTree.Nodes);
            tocTree.SetEnableAll(RoleAccess.GetRoleTocRel(r.ID), tocTree.Nodes);
            resourceTree.SetEnableAll(RoleAccess.GetRoleResRel(r.ID), resourceTree.Nodes);
            mxdTree1.SetEnableAll(RoleAccess.GetRoleMXDRel(r.ID), mxdTree1.Nodes);
            if (r.Extent_Right == null || r.Extent_Right.Length == 0) ctlRegion1.CheckedValues = "";                
            else ctlRegion1.CheckedValues = Encoding.UTF8.GetString(r.Extent_Right);
            _Changed = false;
            funcTree.ResetControl();
            tocTree.ResetControl();
            resourceTree.ResetControl();
            mxdTree1.ResetControl();
            ctlRegion1.ResetControl();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllChk_Click(object sender, EventArgs e)
        {
          
             SetEnableAll(true);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNoAllChk_Click(object sender, EventArgs e)
        {
            SetEnableAll(false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enable"></param>
        private void SetEnableAll(bool enable)
        {
            if (tbctlPrivilege.SelectedTab == tbitmFunc)
            {
                funcTree.SetEnableAll(enable, funcTree.SelectedNodes);
                funcTree.SelectedNodes.Clear();
            }
            else if (tbctlPrivilege.SelectedTab == tbitmToc)
            {
                tocTree.SetEnableAll(enable, tocTree.SelectedNodes);
                tocTree.SelectedNodes.Clear();
            }
            else if (tbctlPrivilege.SelectedTab == tbitmData)
            {
                resourceTree.SetEnableAll(enable, resourceTree.SelectedNodes);
                resourceTree.SelectedNodes.Clear();
            }
            else if (tbctlPrivilege.SelectedTab == tbitmExtent)
            {
                ctlRegion1.SetEnableAll(enable);
            }
            else if (tbctlPrivilege.SelectedTab == tbitmMXD)
            {
                mxdTree1.SetEnableAll(enable, mxdTree1.SelectedNodes);
                mxdTree1.SelectedNodes.Clear();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwRoles_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            _Changed = true;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (_OldIndex == -1) return;
                if (dgrdvwRoles.Rows[_OldIndex].Tag == null) return;
                Role r = (Role)dgrdvwRoles.Rows[_OldIndex].Tag;
                if (funcTree.IsChange)
                {
                    SaveRel(funcTree.Nodes, r.ID, "2", RoleAccess.GetRoleFuncRel(r.ID));
                    Application.DoEvents();
                }
                if (tocTree.IsChange)
                {
                    SaveRel(tocTree.Nodes, r.ID, "3", RoleAccess.GetRoleTocRel(r.ID));
                    Application.DoEvents();
                }
                if (mxdTree1.IsChange)
                {
                    SaveRel(mxdTree1.Nodes, r.ID, "4", RoleAccess.GetRoleMXDRel(r.ID));
                    Application.DoEvents();
                }
                if (resourceTree.IsChange)
                {
                    SaveRel(resourceTree.Nodes, r.ID, "1", RoleAccess.GetRoleResRel(r.ID));
                    Application.DoEvents();
                }
                if (_Changed || ctlRegion1.IsChange)
                {
                    r.Name = dgrdvwRoles.Rows[_OldIndex].Cells[dgrdvwcolName.Index].Value.ToString();
                    r.Extent_Right = System.Text.Encoding.UTF8.GetBytes(ctlRegion1.CheckedValues);
                    ManageHelper.DBContext.Update<Role>(r, "id", r.ID);
                    Application.DoEvents();
                }
                _Changed = false;
                funcTree.ResetControl();
                tocTree.ResetControl();
                resourceTree.ResetControl();
                ctlRegion1.ResetControl();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }
        
        /// <summary>
        /// 
        /// </summary>
        private void SaveChange()
        {
            if (_Changed || funcTree.IsChange || tocTree.IsChange || resourceTree.IsChange || ctlRegion1.IsChange)
            {
                DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("当前角色已修改是否保存?");
                if (dlg == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                }
            }
            _Changed = false;
            funcTree.ResetControl();
            tocTree.ResetControl();
            resourceTree.ResetControl();
            mxdTree1.ResetControl();
            ctlRegion1.ResetControl();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="rid"></param>
        /// <param name="reltype">关联的类型：1数据权限；2功能权限；3Toc右键菜单；4模板配置</param>
        /// <param name="_rels"></param>
        private void SaveRel(NodeCollection nodes, string rid, string reltype, List<Role_Rel> _rels)
        {
            foreach (Node nd in nodes)
            {
                if (nd.Nodes.Count > 0)
                    SaveRel(nd.Nodes, rid, reltype, _rels);
                if (nd.Tag == null) continue;
                string id = "";
                if (nd.Tag is IPrivilegeElement)
                    id = ((IPrivilegeElement)nd.Tag).GetKeyName();
                else
                {
                    id = nd.Name;
                }
                Role_Rel rel = null;
                if (_rels != null) rel = _rels.FirstOrDefault<Role_Rel>(t => t.RelID.Equals(id, StringComparison.CurrentCultureIgnoreCase));
                if (nd.Checked)
                {
                    if (rel == null)
                    {
                        Role_Rel r = new Role_Rel()
                        {
                            ID = Guid.NewGuid().ToString(),
                            RoleID = rid,
                            RelID = id,
                            RelType = reltype
                        };
                        ManageHelper.DBContext.Insert<Role_Rel>(r);
                        //新增
                    }
                }
                else
                {
                    if (rel != null)
                    {
                        //删除
                        Dictionary<string, dynamic> wheres = new Dictionary<string, dynamic>();
                        wheres.Add("roleid", rid);
                        wheres.Add("reltype", reltype);
                        wheres.Add("relid", id);
                        ManageHelper.DBContext.Delete("Role_Rel", wheres);
                    }
                }
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
          
            SaveChange();
        }

    }
}
